package servlet;

import anno.Autowired;
import anno.RequestBody;
import anno.ResponseBody;
import com.fasterxml.jackson.core.JsonProcessingException;
import dao.QuestionDao;
import pojo.Question;
import utils.ApiResult;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题目管理Servlet
 */
@WebServlet("/question")
public class QuestionServlet extends BaseServlet {

    @Autowired
    QuestionDao questionDao;

    @ResponseBody
    public ApiResult findAll(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        List<Question> questions = questionDao.findAll();
        return new ApiResult(200, "查询所有题目成功", questions);
    }
    @ResponseBody
    public ApiResult add(HttpServletRequest req, HttpServletResponse resp, @RequestBody Question question) throws SQLException, JsonProcessingException {
        questionDao.insert(question);
        return new ApiResult(200, "添加题目成功", null);
    }

    @ResponseBody
    public ApiResult update(HttpServletRequest req, HttpServletResponse resp, @RequestBody Question question) throws SQLException, JsonProcessingException {
        if (question.getQuestionId() == null) {
            return new ApiResult(400, "题目ID不能为空", null);
        }
        questionDao.update(question);
        return new ApiResult(200, "更新题目成功", null);
    }

    @ResponseBody
    public ApiResult delete(HttpServletRequest req, HttpServletResponse resp, String questionId) throws SQLException {
        questionDao.deleteById(Integer.valueOf(questionId));
        return new ApiResult(200, "删除题目成功", null);
    }

    @ResponseBody
    public ApiResult findPage(HttpServletRequest req, HttpServletResponse resp, String keyword, String pageNum, String pageSize) throws SQLException {
        int page = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);

        List<Question> questions = questionDao.findPage(page, size, keyword);
        long total = questionDao.countByKeyword(keyword);

        Map<String, Object> result = new HashMap<>();
        result.put("list", questions);
        result.put("total", total);

        return new ApiResult(200, "查询题目成功", result);
    }
}
